<?php
namespace event;
use think\facade\Db;
use think\facade\Cache;

class LoginEvent
{
    
	function login($user){
		$data['application_name'] = $user['application_name'];
		$data['username'] = $user['username'];
		$data['url'] = 'http:'.request()->fullUrl();
		$data['ip'] = request()->getRealIp($safe_mode=true);
		$data['useragent'] = request()->header()['user-agent'];;
		$data['create_time'] = time();
		$data['type'] = 1;
		
		Db::name('log')->insert($data);
	}
	
	
	//单点登录，将其他账号session文件删除
	function sso($data){
		if(!config("my.multiple_login")){
			$sessionId = request()->session()->getId();
			$key = md5(request()->header()['host'].trim($data['username']).trim($data['password']));
			if(config('session.type') == 'redis'){
				$redis = new \Redis();
				$redis->connect(config('redis.default.host'), config('redis.default.port'));
				$sessionList = $redis->hGetAll($key);
				foreach($sessionList as $k=>$v){
					$redis->delete($k);
				}
				$redis->hSet($key, $sessionId, '');
			}else{
				$sessionList = Cache::get($key);
				foreach($sessionList as $k=>$v){
					@unlink(base_path().'/runtime/sessions/session_'.$v);
				}
				Cache::push($key, $sessionId);
			}
		}
	}
}